import { Request, Response, NextFunction } from 'express'
import jwt from 'jsonwebtoken'
import { JWT_SECRET } from '../config/jwt'

// 扩展 Request 类型以包含用户信息
declare global {
  namespace Express {
    interface Request {
      user?: {
        id: number
        username: string
      }
    }
  }
}

export const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
  try {
    // 从请求头获取 token
    const authHeader = req.headers.authorization
    if (!authHeader) {
      return res.status(401).json({ code: 401, message: '未提供认证令牌' })
    }

    // 验证 token 格式
    const parts = authHeader.split(' ')
    if (parts.length !== 2 || parts[0] !== 'Bearer') {
      return res.status(401).json({ code: 401, message: '认证令牌格式错误' })
    }

    const token = parts[1]

    // 验证 token
    const decoded = jwt.verify(token, JWT_SECRET) as {
      id: number
      username: string
    }

    // 将用户信息添加到请求对象
    req.user = {
      id: decoded.id,
      username: decoded.username
    }

    next()
  } catch (error) {
    if (error instanceof jwt.JsonWebTokenError) {
      return res.status(401).json({ code: 401, message: '无效的认证令牌' })
    }
    if (error instanceof jwt.TokenExpiredError) {
      return res.status(401).json({ code: 401, message: '认证令牌已过期' })
    }
    return res.status(500).json({ code: 500, message: '认证失败' })
  }
} 